package com.eqdd.yiqidian.ui.gongneng.renshi.train.fragment;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;

import com.bigkoo.pickerview.TimePickerView;
import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.SignListBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.gongneng.renshi.train.QRSignActivity;
import com.eqdd.yiqidian.ui.gongneng.renshi.train.TrainSignInfoActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author 吕志豪 .
 * @date 18-2-1  下午3:06.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SignFragment extends BaseFragment {
    CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private int pageNum;
    private TimePickerView pvDayTime;
    private SlimAdapterEx<SignListBean> slimAdapterEx;
    private int dealPos;

    @Override
    protected void setView() {

    }

    @Override
    protected void initData() {
        SparseArray<String> status = new SparseArray<>(3);
        status.append(0, "发起签到");
        status.append(1, "签到二维码");
        status.append(2, "已完成");
        int type = getArguments().getInt(Config.TYPE);
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_109, new SlimInjector<SignListBean>() {
            @Override
            public void onInject(SignListBean data, IViewInjector injector) {
                injector.text(R.id.tv_theme, data.getTheTheme())
                        .text(R.id.tv_teacher, data.getTeacherName())
                        .text(R.id.tv_target, data.getTrainees())
                        .text(R.id.tv_address, data.getTheplace())
                        .text(R.id.tv_time, data.getTheTrainTime())
                        .text(R.id.bt_sign, status.get(data.getStatus()))
                        .enable(R.id.bt_sign, data.getStatus() != 2)
                        .clicked(R.id.bt_sign, view -> {
                            dealPos = slimAdapterEx.getData().indexOf(data);
                            if (data.getStatus() == 0) {
                                showTimePicker();
                            } else if (data.getStatus() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(Config.BEAN, slimAdapterEx.getDataItem(dealPos));
                                ((BaseActivity) getActivity()).startActivityForResult(QRSignActivity.class, bundle, Config.QR_SIGN);
                            }
                        });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<SignListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<ZhangPageResultBean<List<SignListBean>>>post(HttpConfig.BASE_URL + HttpConfig.TRAIN_SIGN_LIST)
                        .params("page", pageNum)
                        .params("userGuid", AppConstent.user.getGuid())
                        .params("comid", AppConstent.user.getCompanyId())
                        .params("type", type)
                        .converter(new JsonConverter<ZhangPageResultBean<List<SignListBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(listResultBean -> {
                            pageNum = listResultBean.getNextpage();
                            if (listResultBean.getStatus() == 200) {
                                return Flowable.just(listResultBean.getItems() == null ? new ArrayList<SignListBean>() : listResultBean.getItems());
                            } else {
                                ToastUtil.showShort(listResultBean.getMsg());
                                return Flowable.just(new ArrayList<>());
                            }
                        });

            }
        });
        MVCCoolHelper<List<SignListBean>> mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt(Config.ID, slimAdapterEx.getDataItem(position).getId());
                    bundle.putString(Config.THEME, slimAdapterEx.getDataItem(position).getTheTheme());
                    startActivity(TrainSignInfoActivity.class, bundle);
                });
    }
    private void showTimePicker() {
        if (pvDayTime == null) {
            pvDayTime = new TimePickerView.Builder(getActivity(), (date, v) -> OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.TRAIN_NEW_SIGN)
                    .params("userGuid", AppConstent.user.getGuid())
                    .params("comid", AppConstent.user.getCompanyId())
                    .params("comName", AppConstent.user.getCompany())
                    .params("trainTimeId", slimAdapterEx.getDataItem(dealPos).getId())
                    .params("signStartTime", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date))
                    .params("courseStartTime", slimAdapterEx.getDataItem(dealPos).getCourseStartTime())
                    .params("courseEndTime", slimAdapterEx.getDataItem(dealPos).getCourseEndTime())
                    .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                slimAdapterEx.getDataItem(dealPos).setStatus(1);
                                slimAdapterEx.notifyItemChanged(dealPos);
                            }
                        }
                    })).setOutSideCancelable(true)
                    .setType(new boolean[]{true, true, true, true, true, false})
                    .setDate(Calendar.getInstance())
                    .setRange(1900, 2050)
                    .build();
        }
        pvDayTime.show(true);
    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);
    }

    @Override
    public void onClick(View view) {

    }
}
